from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select


class Base(object):
    """ 自定义封装查找元素、点击、输入、获取文本的方法。其中需要初始化传入
    一个driver对象，loc是一个元组代表元素位置，需要传入属性和值，如：
    login_button = (By.id,'submit') """

    def __init__(self, driver):
        self.driver = driver

    def findelement(self, loc, timeout=10):
        try:
            ele = WebDriverWait(self.driver, timeout, 0.3).until(
                    lambda x: x.find_element(*loc))
            return ele
        except:
            print('未定位到元素')
            return ''

    def sendkeys(self, loc, keys_text):
        self.findelement(loc).send_keys(keys_text)

    def click(self, loc):
        self.findelement(loc).click()

    def gettext(self, loc):
        try:
            t = self.findelement(loc).text
            return t
        except:
            print('获取文本失败，返回为空!')
            return ''

    def select_click(self, select_loc, select_index='', select_value='', select_text=''):
        # 判断传入的select类的属性值，然后使用相应的方法来选择select类元素
        s = Select(self.findelement(select_loc))
        if len(select_index) > 0:
            s.select_by_index(select_index)
        elif len(select_value) > 0:
            s.select_by_value(select_value)
        else:
            s.select_by_visible_text(select_text)


if __name__ == '__main__':
    from selenium import webdriver
    from selenium.webdriver.common.by import By

    driver = webdriver.Chrome()
    b = Base(driver)
    user_loc = (By.CLASS_NAME, 'el-input__inner')
    next_loc = (By.XPATH, "//i[@class='userItemImg icon DHCiconfont DHC-tiaozhuan-denglu']")
    pwd_loc = (By.XPATH, "//input[@placeholder='请输入密码']")
    log_button_loc = (By.XPATH, "//i[@class='icon DHCiconfont DHC-tiaozhuan-denglu']")
    welcome_text_loc = (By.XPATH, "//span[@class='userName el-popover__reference']//a")
    plat_sys_loc = (By.TAG_NAME, 'dt')
    # 打开网页
    driver.get('http://172.28.30.2:9000/platform/#/login')
    driver.maximize_window()
    # 输入用户名
    b.sendkeys(user_loc, 'admin')
    # 点击下一步按钮
    b.click(next_loc)
    # 输入密码
    b.sendkeys(pwd_loc, '111111-a')
    # 点击登录按钮
    b.click(log_button_loc)
    # 点击平台系统按钮
    b.click(plat_sys_loc)
    # 获取登录后的用户姓名
    text = b.gettext(welcome_text_loc)
    print(text)
    driver.quit()
